package com.ruoyi.system.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.enums.SysTestRecordEnum;
import com.ruoyi.stu.domain.StuStudentUnit;
import com.ruoyi.stu.mapper.StuStudentUnitMapper;
import com.ruoyi.system.domain.SysTestRecord;
import com.ruoyi.system.mapper.SysTestRecordMapper;
import com.ruoyi.system.service.ITestRecordService;

/**
 * 测试记录Service业务层处理
 */
@Service
public class TestRecordServiceImpl implements ITestRecordService
{
    @Autowired
    private SysTestRecordMapper sysTestRecordMapper;
    @Autowired
    private StuStudentUnitMapper stuStudentUnitMapper;

    /**
     * 查询测试记录列表
     */
    @Override
    public List<SysTestRecord> list(SysTestRecord entity, Date beginTime, Date endTime, Integer pageNum, Integer pageSize, String unitName, String studentName)
    {
    	pageSize = pageSize != null ? pageSize : 10;
    	pageNum = pageNum != null ? pageNum - 1 : 0;
    	Integer start = pageNum * pageSize;
        return sysTestRecordMapper.list(entity, beginTime, endTime, start, pageSize, unitName, studentName);
    }

    /**
     * 新增测试记录
     */
    @Override
    public int insertTestRecord(SysTestRecord entity)
    {
        int result = sysTestRecordMapper.insertTestRecord(entity);
        
        // 若单元已完成
        if (entity.getPassed() == true) {
            Long studentId = entity.getStudentId();
            Long unitId = entity.getUnitId();
            StuStudentUnit stuStudentUnit = stuStudentUnitMapper.selectByStudentIdAndUnitId(studentId, unitId);
            if (entity.getTestType().equals(SysTestRecordEnum.TestType.DICTATION.value)) {
				if (stuStudentUnit.getStateDictation() == 0) {
					stuStudentUnitMapper.updateStateByStudentIdAndUnitId(studentId, unitId, "state_dictation", 1);
				}
			} else if (entity.getTestType().equals(SysTestRecordEnum.TestType.WRITING.value)) {
				if (stuStudentUnit.getStateWriting() == 0) {
					stuStudentUnitMapper.updateStateByStudentIdAndUnitId(studentId, unitId, "state_writing", 1);
				}
			}
		}
        return result;
    }

    /**
     * 根据用户ID查询测试记录
     * 
     * @param userId 用户ID
     * @return 测试记录集合
     */
    @Override
    public List<SysTestRecord> selectTestRecordsByUserId(Long userId)
    {
        return sysTestRecordMapper.selectTestRecordsByUserId(userId);
    }
}